package com.itheima.edu.info.manager.dao;

import com.itheima.edu.info.manager.domain.Student;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;

/*
库管类:
核心职责管理我们的数据仓库--数组或集合
这里的所有方法和功能都是给业务层用
 */
public class OtherStudentDao05 implements BaseStudentDao {
    private static ArrayList<Student> stu = new ArrayList<>();


    static {
        try {
            FileInputStream fis = new FileInputStream("itheima-edu-info-manager\\stu4.txt");
            byte[] bytes = new byte[1024];
            int len;
            String s = "";
            while ((len = fis.read(bytes)) != -1) {
                s += new String(bytes, 0, len);
            }
//            System.out.println(s);
            String[] split = s.split(System.lineSeparator());
            for (String s1 : split) {
                String[] split1 = s1.split(",");
                Student student = new Student(split1[0], split1[1], split1[2], split1[3]);
                stu.add(student);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public boolean addStudent(Student student) {
        boolean add = stu.add(student);
        reSave();
        return add;
    }


    public Student[] findAllStudent() {
        Student[] stus = new Student[stu.size()];
        Student[] students = stu.toArray(stus);
        return students;
    }

    public void deleteStudent(String delId) {
        int index = getIndex(delId);
        stu.remove(index);
        reSave();
    }

    public int getIndex(String id) {
        int index = -1;
        for (int i = 0; i < stu.size(); i++) {
            Student student = stu.get(i);
            if (student != null && student.getSid().equals(id)) {
                index = i;
            }
        }
        return index;
    }

    public void updateStudent(String updateId, Student newStu) {

        int index = getIndex(updateId);
        stu.set(index, newStu);
        reSave();
    }

    public void reSave() {
        try {
            FileOutputStream fos = new FileOutputStream("itheima-edu-info-manager\\stu4.txt");
            for (Student student : stu) {
                byte[] bytes = student.toString().getBytes();
                fos.write(bytes);
                fos.write(System.lineSeparator().getBytes());
                fos.flush();
            }
            fos.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
